package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 习题类：管理一套习题（支持加法、减法、混合题型）
 */
public class Exercise {
    private final String title;
    private final List<AbstractExpression> expressions = new ArrayList<>();
    private static final Random random = new Random();
    private static final int MAX_NUM = 100; // 运算数范围：1-100

    public Exercise(String title) {
        this.title = title;
    }

    // 生成指定数量的加法题
    public void generateAddExercises(int count) {
        for (int i = 0; i < count; i++) {
            int num1 = random.nextInt(MAX_NUM) + 1;
            int num2 = random.nextInt(MAX_NUM) + 1;
            expressions.add(new AddExpression(num1, num2));
        }
    }

    // 生成指定数量的减法题
    public void generateSubtractExercises(int count) {
        for (int i = 0; i < count; i++) {
            int num1 = random.nextInt(MAX_NUM) + 1;
            int num2 = random.nextInt(MAX_NUM) + 1;
            expressions.add(new SubtractExpression(num1, num2));
        }
    }

    // 新增：生成指定数量的加减法混合题（约各占50%）
    public void generateMixedExercises(int count) {
        for (int i = 0; i < count; i++) {
            int num1 = random.nextInt(MAX_NUM) + 1;
            int num2 = random.nextInt(MAX_NUM) + 1;
            // 随机选择加法或减法
            if (random.nextBoolean()) {
                expressions.add(new AddExpression(num1, num2));
            } else {
                expressions.add(new SubtractExpression(num1, num2));
            }
        }
    }

    // 优化：格式化显示（每页10题，每行2题，带分页）
    public void printExercises() {
        System.out.println("\n===== " + title + " =====");
        for (int i = 0; i < expressions.size(); i++) {
            // 每10题分页
            if (i != 0 && i % 10 == 0) {
                System.out.println("\n----- 第" + (i / 10 + 1) + "页 -----");
            }
            // 格式化输出：通过索引获取单个算式对象，再调用其方法
            System.out.printf("%2d. %s = ?   ", (i + 1), expressions.get(i).getExpressionStr());
            // 每行显示2题
            if ((i + 1) % 2 == 0) {
                System.out.println();
            }
        }
        System.out.println("\n===========================");
    }

    public List<AbstractExpression> getExpressions() {
        return new ArrayList<>(expressions);
    }
}